/**
 * 
 * autho:zxhuan 
 * email:1123046380@qq.com
 * blog (http:www.zxhuan.com)
 * @date    2016-09-22 11:31:05
 * @version $Id$
 */

;(function($,window,document,undefined){
	// 移动端地址选择插件
	$.fn.mobileAddress=function(options){
		self.flag=false;//boolean,通过控制true or false, 防止恶意切换
		self.text=null;//回调时,用来储存选择到的地址数据
		this.default={
			"ajaxURL":"#",//ajax请求数据的地址
			"speed":300,//切换的速度
			storageBox:"",//在选择地址用，用来储存地址数据的盒子
			callback:function(){}
		}
		this.option=$.extend({},this.default,options);
		var arrText="";//储存选择到的数据，添加到storageBox中
		var op=this.option;
		// 初始化入口
		this.init=function(){
			var self=this;
			this.createEle();
			this.createProvince();
			// 点击关闭按钮的时候按钮的时候
			self.closeBtn.on("click",function(){
				self.maskHidie();
			})
           	self.aInfo.on("click",function(event){
		    	var index=$(this).index();
		    	self.clickInfo($(this),index);
		    	event.stopPropagation();
		    	event.preventDefault();
			});
			self.mask.on("click",function(event){
				if($(event.target).attr("id")=="toogle-mask"){
					self.maskHidie();
				}
			})
		}
		// 创建toogle-mask模块
		this.createEle=function(){
			var self=this;
			self.mask=$('<div class="toogle-address-mask" id="toogle-mask"></div>');
			self.maskChild=$('<div class="toogle-address" id="toggleCont"><div class="toogle-address-title border-b">请选择地址<i class="icon icon-close" id="closeBtn"></i></div><div id="address" class="address"><div class="address-header border-b"><span class="address-info address-now" id="provience">请选择</span><span class="address-info" id="city">请选择</span><span class="address-info" id="county">请选择</span></div><div class="address-content"><div class="address-cont"><ul class="provienc-part" data-create="createCity" data-index="1"></ul><ul class="city-part" data-create="createCounty" data-index="2"></ul><ul class="county-part" data-index="3"></ul></div></div></div></div>');
			$("body").append(self.mask);
			self.mask.append(self.maskChild);
			self.closeBtn=$("#closeBtn",self.mask);//关闭按钮
			self.toogleMask=$("#toggleCont",self.mask);//选择地址的内容区
			self.aInfo=$(".address-info",self.mask);//选择省市区选项
			self.AddressCont=$(".address-cont",self.mask);//三个地址列表包裹的层
			self.mask.css({"opacity":"1"})
			self.maskChild.css({
				"bottom":'-300px',
				"transition":"all ease "+(op.speed/1000)+"s"
			});
			var timer=setTimeout(function(){
				var flag=true;
				if(flag){
					flag=false;
					self.maskChild.css({
						"left":"0",
						"bottom":"0"
					})
					flag=true;
					clearTimeout(timer);
				}
			},100)
		}
		// 创建省模块
		this.createProvince=function(){
			var self=this;
			 // self.addressAjax(self.AddressCont.find('.provienc-part'),null,1);
			 self.addressAjax($('.provienc-part'),null,1);
		}
		// 创建市模块
		this.createCity=function(dataValue){
			var self=this;
			 self.mask.find("#city").show();
			 self.AddressCont.find('.city-part').empty();
			self.addressAjax(self.AddressCont.find('.city-part'),dataValue,2);
		}
		// 创建区域模块
		this.createCounty=function(dataValue){
			var self=this;
			 self.mask.find("#county").show();
			 self.AddressCont.find('.county-part').empty();
			self.addressAjax(self.AddressCont.find('.county-part'),dataValue,3);
		}
		// 点击选择地址
		this.clickfn=function (district){
			var self=this;
			district.on('click',function(event){
				if(!district.parent().hasClass("addressActive")){
					var _this=$(this);
					var parent=_this.parent();
					var dataValue=_this.data("value");
					var parentCreate=parent.data("create");
					var dataIndex=parent.data("index");
					district.parent().addClass("addressActive");
	          		_this.parent().find('li').removeClass("liNow");
	          		_this.addClass("liNow");
					self.aInfo.eq(dataIndex-1).attr("data-value",dataValue).html(_this.text());
					if(parentCreate=='createCity'){
						self.createCity(dataValue);
					}else if(parentCreate=="createCounty"){
						self.createCounty(dataValue);
					}
					if(dataIndex==3){
						// 如果dataIndex=3,说明选择的是区域，执行移除toogle-address模块
						self.maskHidie();
					}else{
						// 如果dataIndex小于3，执行clickInfo
						self.clickInfo(self.aInfo.eq(dataIndex),dataIndex);
					}
				}
			})
		}
		// 移除toogle-address模块
		this.maskHidie=function(){
			var self=this;
			self.maskChild.css({
				"bottom":'0px'
			});
			var timer=setTimeout(function(){
				self.maskChild.css({
					"bottom":'-300px'
				})
				self.addressInput();
				if(op.callback&& typeof op.callback=="function"){
					// 执行回调函数
					var addressArr=[];
					for(var i=0;i<self.aInfo.length;i++){
						if(self.aInfo.eq(i).data("value")){
							addressArr.push(self.aInfo.eq(i).data("value"))
						}
					}
					/*
					self.text:地址
					addressArr：地址对应的坐标
					*/
					op.callback(self.text,addressArr);
					clearTimeout(timer);
				}
			},100)
		}
		// 将数据存放到input表单中
		this.addressInput=function(){
			var self=this;
			var boxHtml="";
			var text="";
			self.text="";
			for(var i=0;i<op.storageBox.find("span").length;i++){
				boxHtml+=op.storageBox.find("span").eq(i).text()+" ";
			}
			for(var i=0;i<$(".liNow").length;i++){
				arrText+="<span>"+$(".liNow").eq(i).text()+"</span>";
				text+=$(".liNow").eq(i).text()+" ";
			};
			// 如果arrText不为空
			if(arrText!=""){
				// op.storageBox.html(arrText);
				self.text=text;
			}else{
				self.text=boxHtml;
			}
			setTimeout(function(){
				self.mask.css("opacity",0);
				self.mask.remove();
			},300);
		}
		this.clickInfo=function(ele,index){
			var self=this;
			self.flag=true;
			if(self.flag){
				self.flag=false;
				ele.addClass("address-now").siblings().removeClass("address-now");
				self.AddressCont.css({
					"transition":"all cubic-bezier(0, 1, 0, 1.47) "+op.speed
				})
				setTimeout(function(){
					self.AddressCont.css({
						"margin-left":"-"+index*100+"%"
					});
				},300)
				// self.AddressCont.animate({
				// 	"margin-left":"-"+index*100+"%"
				// },op.speed);
				self.flag=true;
			}
		}
		// 通过ajax请求数据
		this.addressAjax = function(district, cValue, ov,type) {
			// console.log(district, cValue, ov,type)
			var self=this;
            var oType = null;
			district.empty();
            $.ajax({
               url: this.option.ajaxURL,
               dataType: 'JSON',
               success: function(data) {
				   console.log(data);
 				// var data=JSON.parse(data);
               	district.empty();
                   if (ov == 3) {
                       oType = data.county; //请求区的数据
                   } else if (ov == 2) {
                       oType = data.city; //请求市的数据
                   } else if (ov == 1) {
                       oType = data.provience; //请求省的数据
                   }
                   this.countyItem='';
                  
                   $.each(oType, function(key, value) {
                       if (cValue == null) {
                             this.countyItem =  $("<li data-value='" + value.id + "'>" + value.name + "</li>");
                       } else if (cValue == value.cid) {
                             this.countyItem = $("<li data-value='" + value.id + "'>" + value.name + "</li>");
                       }
                       district.append(this.countyItem);
                   });
              		self.clickfn(district.find("li"));
               },
               error: function() {
                   console.log('ajax error')
               }
           })
       }
		return this.init();
	}
	// dialog对话框
	$.fn.dialog=function(options){
		function Dialog(options){
			this.defalut={
				width:250,//dialog[width]
				height:200,//dialog[heidht]
				dialogHeader:false,//是否显示头部
				dialogHeaderText:"温馨提示！",//头部的文字
				dialogType:"confirm",//[alert,confirm,prompt]
				message:"您确定要删除吗？",//内容区显示的文字
				alertBtn:"确定",//alertBtn的文字
				confirmTrueBtn:"确定",//confirmTrueBtn的文字
				confirmFalseBtn:"取消",//confirmFalseBtn的文字
				promptTrueBtn:"确定",//promptTrueBtn的文字
				promptFalseBtn:"取消",//promptFalseBtn的文字
				alertCall:null,//点击alertBtn是的回调函数
				confirmTrueCall:null,//confirmTrueBtn的回调函数
				confirmFalseCall:null,//confirmFalseBtnd的回调函数
				promptTrueCall:null,//promptTrueBtn的回调函数
				promptFalseCall:null,//promptFalseBtnd的回调函数
			}
			this.o=$.extend({},this.defalut,options);
			this.handlers={};
			this.init(options);
		};
		Dialog.prototype={
			init:function(options){// 初始化入口
				this.bluid();
				this.handler();
			},
			bluid:function(){//接口：添加dom节点
				var $this=this,
					o= this.o,
					mask=$this.mask=$('<div class="dialog-mask"></div>'),
					dialog=$this.dialog=$('<div class="dialog"></div>'),
					header=$this.dialogHeader=$('<h2 class="dialog-header"></h2>'),
					content=$this.dialogContent=$('<div class="dialog-content"></div>'),
					btnGroup=$this.btnGroup=$('<div class="dialog-btn-group"></div>');
				$this.animates(dialog,"show");
				if(o.dialogHeader){
					dialog.append(header.html(o.dialogHeaderText));
				}
				
				switch(o.dialogType) {
					case "alert":
						content.append(o.message);
						btnGroup.append('<a href="javascript:;" class="link-flex btn-red alertBtn">'+o.alertBtn+'</a>')
						break;
					case "confirm":
						content.append(o.message);
						btnGroup.append('<a href="javascript:;" class="link-flex confirmTrueBtn" data-value="true">'+o.confirmTrueBtn+'</a><a href="javascript:;" class="link-flex btn-red confirmFalseBtn" data-value="false">'+o.confirmFalseBtn+'</a>');
						break;
					case "prompt":
						content.append('<input type="text" value="" class="prompt-input" placeholder='+o.message+'>');
						btnGroup.append('<a href="javascript:;" class="link-flex promptTrueBtn">'+o.promptTrueBtn+'</a><a href="javascript:;" class="link-flex btn-red promptFalseBtn" >'+o.promptFalseBtn+'</a>');
						break;
				}
				dialog.append(content);
				dialog.append(btnGroup);
				$("body").append(mask.append(dialog));
			},
			animates:function(ele,type){//接口,显示与移除的动画
				var $this=this;
				var o=this.o;
				switch(type) {
					case "show":
						var timer=null;
	    				ele.css({
	    					"width":o.width,
	    					"opacity":0,
	    					"position":"absolute",
	    					"top":"-50%",
	    					"left":"50%",
	    					"transition":"all ease 0.5s"
	    				})
	    				timer=setTimeout(function(){
	    					var flag=true;
	    					if(flag){
	    						flag=false;
								ele.css({
			    					"opacity":1,
									"top":"50%",
									"left":"50%",
		    					});
		    					flag=true;
		    					clearTimeout(timer);
	    					}
	    				},5)
						break;
					case "remove":
						ele.css({
	    					"transition":"all ease 0.5s"
	    				})
	    				var time=setTimeout(function(){
	    					var flag=true;
	    					if(flag){
	    						flag=false;
								ele.css({
			    					"opacity":0
		    					});
		    					flag=true;
		    					clearTimeout(time);
		    					ele.parent().remove();
	    					}
	    				},10)
						break;
				}
			},
			handler:function(){//接口：监听事件
				var $this=this;
				var o= this.o;
				$this.mask.delegate(".alertBtn","click",function(){
					$this.trigger("alert");
					$this.destory();
				})
				$this.mask.delegate(".confirmTrueBtn","click",function(){
					var value=$(this).data("value");
					$this.trigger("confirmTrueBtn",value);
					$this.destory();
				})
				$this.mask.delegate(".confirmFalseBtn","click",function(){
					var value=$(this).data("value");
					$this.trigger("confirmFalseBtn",value);
					$this.destory();
				})
				$this.mask.delegate(".promptTrueBtn","click",function(){
					var value=$(".dialog-content",$this.mask).find("input").val();
					$this.trigger("promptTrueBtn",value);
					$this.destory();
				})
				$this.mask.delegate(".promptFalseBtn","click",function(){
					$this.trigger("promptFalseBtn");
					$this.destory();
				})
				if(o.alertCall){
					$this.on("alert",o.alertCall)
				}
				if(o.confirmTrueCall){
					$this.on("confirmTrueBtn",o.confirmTrueCall)
				}
				if(o.confirmFalseCall){
					$this.on("confirmFalseBtn",o.confirmFalseCall)
				}
				if(o.promptTrueCall){
					$this.on("promptTrueBtn",o.promptTrueCall)
				}
				if(o.promptFalseCall){
					$this.on("promptFalseBtn",o.promptFalseCall)
				}
			},
			on:function(type,handlers){//接口:事件绑定
				this.handlers[type]=[];
				if(typeof this.handlers[type]=="undefined"){
					this.handlers[type]=[];
				}
				this.handlers[type].push(handlers);
			},
			trigger:function(type,data){//接口:事件触发
				if(this.handlers[type] instanceof Array){
					var handlers=this.handlers[type];
					for(var i=0;i<handlers.length;i++){
						handlers[i](data);
					}
				}
			},
			destory:function(){//销毁dialog
				this.animates($('.dialog',this.mask),"remove")
			}
		}
		return this.each(function(){
			new Dialog(options);
		});
	}
	    /**
     * / 滚动条回到顶部
     * @param  {[type]} option [description]
     * @return {[type]}        [description]
     */
    $.fn.backTop = function(option) {
        var $this = this;
        $this.default = {
            speed: 8, //返回顶部时的速度
            autoShow: false, //滚动条滚到到指定高度的时候，是否隐藏，默认为false【hide】
            scrollTop: 100 //滚动条滚到到指定高度【autoShow 为false时】
        }
        $this.timer = null;
        $this.options = $.extend({}, this.default, option);
        function scrollFn() {
            var scrollT = parseInt(document.body.scrollTop) || parseInt(document.documentElement.scrollTop) || parseInt(window.pageYOffset);
            if (scrollT < $this.options.scrollTop) {
               $this.hide()
            } else {
                 $this.show()
            }
        }
        if (!$this.options.autoShow) {
            $this.hide();
            $(window).on('scroll', function() {
                scrollFn();
            });
            scrollFn();
        }
        $this.on('click click touchstart', function() {
            var scrollT = parseInt(document.body.scrollTop) || parseInt(document.documentElement.scrollTop) || parseInt(window.pageYOffset);
            var speed = 0;
            $this.timer = setInterval(function() {
                speed = Math.ceil(scrollT / 50);
                if (scrollT > 0) {
                    scrollT -= speed;
                    document.body.scrollTop = scrollT;
                    document.documentElement.scrollTop = scrollT;
                    window.pageYOffset = scrollT;
                } else {
                    clearInterval($this.timer)
                }
            }, $this.default.speed);
        })
    }
	// tab选项卡
	$.fn.myTab=function(options){
		return this.each(function(){
			var option=$.extend({parent:'',index : null},options);
			$(this).find('li').on('click',function(){
				var $this=$(this),
					$index=$this.index()+1;
					$this.addClass("cur").siblings().removeClass('cur');
					$(options.parent).children(':nth-child('+$index+')').addClass('on').siblings().removeClass('on')
			})
			if(options.index == null){
				$(this).find('li').eq(0).click();
			}else{
				$(this).find('li').eq(options.index).click();
			}
		})
	}
})(jQuery,window,document);
